<?php
class model_PhotoMapper {
    private $table = 'photos';

    public function  __construct() {
        model_ConfigMapper::connect();
    }

    public function getTable() {
        return $this->table;
    }

    public function find($id) { //находим сообщение, записываем его содержание в свойства объекта
        $query = 'SELECT * from '. $this->table .' WHERE id = '. $id;
        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);

        if ($row) {
            $m = new model_PhotoModel($row);
        } else {
            $m = new model_PhotoModel(null);
        }

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
        
        return $m;
    }

    public function fetchAll($id) { //
        $query = 'SELECT * from '. $this->table .' where owner ='. $id ;
        $result = mysql_query($query);

        $entries = array();

        while ($row = mysql_fetch_assoc($result)) {
            $entry = new model_PhotoModel($row);
            $entries[] = $entry;
        }

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $entries;
    }

    public function save($model) {
        if('' == $model->getId()) {
            $query = 'INSERT INTO '.$this->table.' (owner, title, name) VALUES ("'. $model->getOwner() .'","'. $model->getTitle() .'","'. $model->getName() .'")';
        } else {
            $query = 'UPDATE '.$this->table.' SET title="'. $model->getTitle() .'" WHERE id="'. $model->getId() .'"' ;
        }

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        $result = mysql_query($query);
    }

    public function delete($id) { // собственно удаляем

        $query = 'SELECT name FROM photos WHERE id='. $id ;
        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        unlink('stuff/images/saved/'. $row['name'] .'.jpg');         //удаляем картинку

        $query = 'DELETE FROM '.$this->table.' WHERE id="'.$id.'"';
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }
}